import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userInfo = ref(null)
  const token = ref(localStorage.getItem('token') || '')
  const refreshToken = ref(localStorage.getItem('refreshToken') || '')

  // 设置用户信息
  function setUserInfo(info) {
    userInfo.value = info
  }

  // 设置 Token
  function setToken(newToken, newRefreshToken) {
    token.value = newToken
    refreshToken.value = newRefreshToken
    
    localStorage.setItem('token', newToken)
    localStorage.setItem('refreshToken', newRefreshToken)
    localStorage.setItem('tokenExpireTime', Date.now() + 30 * 60 * 1000)
  }

  // 清除用户信息
  function clearUserInfo() {
    userInfo.value = null
    token.value = ''
    refreshToken.value = ''
    
    localStorage.removeItem('token')
    localStorage.removeItem('refreshToken')
    localStorage.removeItem('tokenExpireTime')
    localStorage.removeItem('userInfo')
  }

  // 登出
  function logout() {
    clearUserInfo()
  }

  // 检查是否已登录
  function isLoggedIn() {
    return !!token.value
  }

  return {
    userInfo,
    token,
    refreshToken,
    setUserInfo,
    setToken,
    clearUserInfo,
    logout,
    isLoggedIn
  }
})

